import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../screens/home_screen.dart';
import '../screens/chat_detail_screen.dart';
import '../stores/chat_store.dart';

// 路由配置类
class AppRouter {
  final ChatStore chatStore;

  AppRouter({required this.chatStore});

  // 获取GoRouter实例
  GoRouter get router => GoRouter(
    initialLocation: '/',
    // 路由配置
    routes: [
      // 主页路由 - 包含底部导航栏
      GoRoute(
        path: '/',
        name: 'home',
        builder: (context, state) => const HomeScreen(),
        // 子路由
        routes: [
          // 聊天详情页
          GoRoute(
            path: 'chat/:chatId',
            name: 'chatDetail',
            pageBuilder: (context, state) {
              // 获取路由参数
              final chatId = state.pathParameters['chatId'] ?? '';
              // 设置当前聊天ID
              chatStore.selectChat(chatId);

              return CustomTransitionPage(
                key: state.pageKey,
                child: const ChatDetailScreen(),
                transitionsBuilder:
                    (context, animation, secondaryAnimation, child) {
                      // 从右向左的过渡动画
                      const begin = Offset(1.0, 0.0);
                      const end = Offset.zero;
                      const curve = Curves.easeInOut;
                      var tween = Tween(
                        begin: begin,
                        end: end,
                      ).chain(CurveTween(curve: curve));
                      var offsetAnimation = animation.drive(tween);

                      return SlideTransition(
                        position: offsetAnimation,
                        child: child,
                      );
                    },
              );
            },
          ),
        ],
      ),
    ],
    // 当路由发生错误时的处理
    errorBuilder: (context, state) {
      return Scaffold(
        appBar: AppBar(title: const Text('页面未找到')),
        body: Center(child: Text('找不到页面: ${state.uri.path}')),
      );
    },
  );
}
